package com.trendata.service.wechat;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.trendata.domain.Shop;
import com.trendata.domain.User;
import com.trendata.domain.wechat.TextMessage;
import com.trendata.service.CacheService;
import com.trendata.service.ShopService;
import com.trendata.service.UserService;
import com.trendata.util.Constants;
import com.trendata.util.MessageUtil;
import com.trendata.util.ResultDO;
import com.trendata.util.TimeUtil;
import com.trendata.util.WeChatUtil;

/**
 * 核心服务类
 * 
 * @author liufeng
 * @date 2013-05-20
 */
@Service("weChatService")
public class WechatService {

	@Autowired
	private UserService userService;
	@Autowired
	private CacheService cacheService;
	@Autowired
	private ShopService shopService;

	private static Logger logger = Logger.getLogger("wechatLogger");

	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			logger.info(JSONObject.fromObject(requestMap).toString());
			// 发送方帐号（open_id）
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			// 回复文本消息
			TextMessage respTextMessage = new TextMessage();
			respTextMessage.setToUserName(fromUserName);
			respTextMessage.setFromUserName(toUserName);
			respTextMessage.setCreateTime(new Date().getTime());
			respTextMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			User user = (User) request.getSession().getAttribute(Constants.SESSION_OPEN_ID);
			boolean isFirst = false;
			if (user == null) {
				// 数据库是否存在
				user = userService.selectByOpenId(fromUserName);
				if (user == null) {
					// 新用户
					isFirst = true;
					String accessToken = cacheService.getAccessToken(TimeUtil.getCurrentHour());
					ResultDO<User> userResultDO = WeChatUtil.getUser(accessToken, fromUserName);
					if (userResultDO.isSuccess()) {
						user = userResultDO.getModule();
						userService.insert(user);
						request.getSession().setAttribute(Constants.SESSION_OPEN_ID, user);
					} else {
						respContent = userResultDO.getErrMsg();
					}
				}
			}
			if (user != null) {
				if (msgType.equals(MessageUtil.RESP_MESSAGE_TYPE_TEXT)) {
					respContent = "这是一个文本信息";
				}
				// 事件推送
				else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
					// 事件类型
					String event = requestMap.get("Event");
					// 用户扫描的永久二维码的ticket
					String ticket = requestMap.get("Ticket");
					// 关注事件
					if (event.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
						if (!isFirst) {
							user.setSubscribe(true);
							user.setSubscribeTime(new Date().getTime());
							userService.update(user);
						}
						respContent = this.respByTicket(ticket, fromUserName);
					}
					// 取消订阅
					else if (event.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
						user.setSubscribe(false);
						userService.update(user);
					}
					// 扫码事件
					else if (event.equals(MessageUtil.EVENT_TYPE_SCAN)) {
						// TODO 扫码
						respContent = this.respByTicket(ticket, fromUserName);
					}
				} else {
					respContent = "感谢您的关注！";
				}
			}
			respTextMessage.setContent(respContent);
			respMessage = MessageUtil.textMessageToXml(respTextMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return respMessage;
	}

	private String respByTicket(String ticket, String userOpenId) {
		if (ticket == null || userOpenId == null) {
			return "感谢对趋数网络的关注！";
		}
		Shop shop = shopService.selectByTicket(ticket);
		if (shop == null) {
			return "感谢对趋数网络的关注！";
		}
//		>>>>点击进入拍逛<<<<
		return "开始您的逛拍之旅吧！\n<a href=\"http://www.chizhishi.cn/snapshot/mobile/index.html?shopOpenId=" + shop.getOpenId() + "&openId="
				+ userOpenId + "\">>>>>点击进入拍逛<<<<</a>";
	}
}
